package com.weixiao.config;

import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;
import com.github.pagehelper.PageInterceptor;
import org.apache.ibatis.logging.stdout.StdOutImpl;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import javax.sql.DataSource;
import java.util.Properties;

@Configuration
@MapperScan(basePackages = "com.weixiao.dao.ryvue", sqlSessionFactoryRef = "ryVueSqlSessionFactory")
public class RyVueDataSourceConfig {

    @Bean("ryVueDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.ry-vue")
    public DataSource getRyVueDataSource(){
        return DataSourceBuilder.create().build();
    }

    @Bean("ryVueSqlSessionFactory")
    public SqlSessionFactory ryVueSqlSessionFactory(@Qualifier("ryVueDataSource") DataSource dataSource) throws Exception {
        MybatisSqlSessionFactoryBean bean = new MybatisSqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath*:mappers/ryvue/*.xml"));

        //此处创建一个Configuration 注意包不要引错了
        org.apache.ibatis.session.Configuration configuration=new org.apache.ibatis.session.Configuration();
        //配置日志实现
        configuration.setLogImpl(StdOutImpl.class);
        //此处可以添加其他mybatis配置 例如转驼峰命名
        configuration.setMapUnderscoreToCamelCase(true);

        //分页插件
        Interceptor[] interceptors = new Interceptor[1];
        interceptors[0] = new PageInterceptor();

        Properties properties = new Properties();
        //开启分页判断：分页页数大于总页数时显示最后一页，小于等于0时显示第一页，默认关闭
        properties.setProperty("reasonable","true");

        interceptors[0].setProperties(properties);
        bean.setPlugins(interceptors);

        return bean.getObject();
    }

    @Bean("ryVueSqlSessionTemplate")
    public SqlSessionTemplate ryVueSqlSessionTemplate(@Qualifier("ryVueSqlSessionFactory") SqlSessionFactory sqlSessionFactory){
        return new SqlSessionTemplate(sqlSessionFactory);
    }
}
